import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE,
  timeout: 15000,
})

// 请求拦截器
service.interceptors.request.use((config) => {
  config.headers['X-Token'] = getToken()
  return config
})

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.code !== 200) {
      showToast(response.data.message)
      return Promise.reject(response.data)
    }
    return response.data
  },
  (error) => {
    // 统一错误处理
    const status = error.response?.status
    switch (status) {
      case 401:
        // 处理未授权
        window.location.href = '/login'
        break
      case 403:
        // 处理禁止访问
        break
      case 500:
        // 处理服务器错误
        break
      default:
        console.error('请求错误:', error.message)
    }

    return Promise.reject(error)
  }
)

export default service
